// server/TestMqttCommand.js
import mqttServer from './MqttServer.js';

const sn = '02100824090900030075';

function getVoltageParameter() {
    const deviceAddress = 2;  // 从机地址
    const functionCode = 4;   // 功能码
    const registerAddress = 312;  // 寄存器起始地址
    const dataType = mqttServer.DataType.FLOAT32_ABCD;  // 32位浮点数(ABCD)
    const pollingInterval = 1;  // 轮询时间（秒）

    mqttServer.getSingleData(sn, deviceAddress, functionCode, registerAddress, dataType, pollingInterval);
}

// 等待连接成功后再订阅和发送命令
mqttServer.client.on('connect', () => {
    console.log('MQTT 客户端已连接，开始订阅主题');
    
    // 订阅特定设备的主题
    const pubTopic = `youren/+/PubTopic`;
    mqttServer.client.subscribe(pubTopic, { qos: 1 }, function(err) {
        if (!err) {
            console.log(`成功订阅主题：${pubTopic}`);
            getVoltageParameter();
        } else {
            console.error('订阅失败:', err);
        }
    });
});

// 确保程序不会立即退出
process.on('SIGINT', () => {
    console.log('正在关闭 MQTT 客户端...');
    mqttServer.client.end(true, () => {
        console.log('MQTT 客户端已关闭');
        process.exit(0);
    });
});